package com.jisf.driver.auth;

import com.jisf.driver.response.Result;
import com.jisf.driver.response.ResultCode;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Classname MyAuthenticationFailureHandler
 * @Description TODO 登录失败时的处理器
 * @Date 2022/3/22 22:48
 * @Created by jisf：【429627912@qq.com】
 */
@Component("myAuthenticationFailureHandler")
public class MyAuthenticationFailureHandler extends JsonAuthentication implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        //返回json数据
        Result result = null;
        if (e instanceof AccountExpiredException){
            //账号过期
            result = Result.error(ResultCode.USER_ACCOUNT_EXPIRED);
        }else if (e instanceof BadCredentialsException){
            //密码错误
            result = Result.error(ResultCode.USER_CREDENTIALS_ERROR);
        }else if (e instanceof CredentialsExpiredException){
            //密码过期
            result = Result.error(ResultCode.USER_CREDENTIALS_EXPIRED);
        }else if (e instanceof DisabledException){
            //账号不可用
            result = Result.error(ResultCode.USER_ACCOUNT_DISABLE);
        }else if (e instanceof LockedException){
            //账号锁定
            result = Result.error(ResultCode.USER_ACCOUNT_LOCKED);
        }else if (e instanceof InternalAuthenticationServiceException){
            //用户不存在
            result = Result.error(ResultCode.USER_ACCOUNT_NOT_EXIST);
        }else {
            //其他错误
            result = Result.error(ResultCode.LOGIN_FAILED);
        }
//        response.setContentType("text/json;charset=utf-8");
//        response.getWriter().write(new ObjectMapper().writeValueAsString(result));
        this.WriteJSON(request, response, result);
    }
}
